package cn.com.homeyoda.aimate.aihealth.ui.my.family.manage;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.ADD_FAMILY_MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.DELETE_FAMILY_MEMBER;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.UPDATE_FAMILY_NAME;
import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.UPDATE_MEMBER;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.FamilyMembersBean;
import cn.com.homeyoda.aimate.aihealth.bean.MultipleItem;
import cn.com.homeyoda.aimate.aihealth.bean.PromptUserListBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityManageBinding;
import cn.com.homeyoda.aimate.aihealth.ui.my.family.FamilyViewModel;
import cn.com.homeyoda.aimate.aihealth.ui.my.family.info.MemberInfoActivity;

public class ManageActivity extends BaseActivity<ActivityManageBinding, FamilyViewModel> implements View.OnClickListener {

    private ManageAdapter manageAdapter;
    private AddMemberAdapter addMemberAdapter;
    private List<MultipleItem<Object>> membersList = new ArrayList<>();

    private LinearLayout llNoMember;
    private ConstraintLayout clMember;
    private MaterialDialog addMemberDialog;

    @Override
    public FamilyViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(FamilyViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_manage;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        binding.titleBar.ivBack.setOnClickListener(this);
        binding.titleBar.tvTitle.setText(getString(R.string.family_management));
        binding.ivEditFamilyName.setOnClickListener(this);
        binding.tvFamilyName.setOnClickListener(this);

        viewModel.getMemberList();

        initRecyclerView();
    }

    private void initRecyclerView() {

        manageAdapter = new ManageAdapter();
        binding.setLayoutManager(new GridLayoutManager(this, 2));
        binding.setAdapter(manageAdapter);
        manageAdapter.setOnItemClickListener((adapter, view, position) -> {
            int type = manageAdapter.getItemViewType(position);
            if (type == MultipleItem.MEMBER) {
                FamilyMembersBean.DataBean.FamilyMembers member  = (FamilyMembersBean.DataBean.FamilyMembers) manageAdapter.getItem(position).getData();
                MemberInfoActivity.start(this, member);
            } else {
                showAddMemberDialog();
            }
        });
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.memberData.observe(this, member -> {
            membersList.clear();
            for (FamilyMembersBean.DataBean.FamilyMembers memberBean : member.getFamilyMembers()) {
                membersList.add(new MultipleItem<>(MultipleItem.MEMBER, memberBean));
            }
            membersList.add(new MultipleItem<>(MultipleItem.ADD, R.string.add_members));
            binding.tvFamilyName.setText(member.getFamilyName());
            binding.tvMemberCount.setText(member.getFamilyMembers().size() + "人");
            binding.rvMembers.scrollToPosition(0);
            manageAdapter.setNewData(membersList);
        });

        viewModel.promptUserData.observe(this, promptUserList -> {
            if (promptUserList.isEmpty()) {
                llNoMember.setVisibility(VISIBLE);
                clMember.setVisibility(GONE);
            } else {
                llNoMember.setVisibility(GONE);
                clMember.setVisibility(VISIBLE);
                if (addMemberAdapter == null) return;
                List<PromptUserListBean.RowsBean> list = new ArrayList<>();
                for (PromptUserListBean.RowsBean rowsBean : promptUserList) {
                    if (!TextUtils.isEmpty(rowsBean.getFaceId())) {
                        list.add(rowsBean);
                    }
                }
                addMemberAdapter.setNewData(list);
            }
        });

        LiveEventBus.get(UPDATE_FAMILY_NAME, String.class).observe(this, binding.tvFamilyName::setText);

        LiveEventBus.get(ADD_FAMILY_MEMBER, Boolean.class).observe(this, aBoolean -> {
            if (!aBoolean) return;
            viewModel.getMemberList();
            if (addMemberDialog != null) {
                addMemberDialog.dismiss();
            }
        });

        LiveEventBus.get(UPDATE_MEMBER, FamilyMembersBean.DataBean.FamilyMembers.class)
                .observe(this, member -> viewModel.getMemberList());

        LiveEventBus.get(DELETE_FAMILY_MEMBER, Boolean.class)
                .observe(this, aBoolean -> viewModel.getMemberList());

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_edit_family_name || id == R.id.tv_family_name) {
            showDialog();
        }
    }

    private void showDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_edit_family_name, false)
                .show();
        TextView tvName = dialog.getView().findViewById(R.id.et_family_name);
        tvName.setText(binding.tvFamilyName.getText().toString());
        dialog.getView().findViewById(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());
        dialog.getView().findViewById(R.id.btn_save).setOnClickListener(v -> {
            viewModel.updateFamilyName(tvName.getText().toString());
            dialog.dismiss();
        });
        if (dialog.getWindow() != null) {
            dialog.getWindow().setLayout(600, 400);
            dialog.getWindow().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(0));
        }
    }

    private void showAddMemberDialog() {
        viewModel.getPromptUserList();

        addMemberDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_add_family_member, false)
                .show();

        llNoMember = addMemberDialog.getView().findViewById(R.id.ll_no_member);
        clMember = addMemberDialog.getView().findViewById(R.id.cl_member);
        addMemberAdapter = new AddMemberAdapter(R.layout.add_member_item);
        RecyclerView rvFamilyMember = addMemberDialog.getView().findViewById(R.id.rv_family_member);
        rvFamilyMember.setLayoutManager(new GridLayoutManager(this, 2));
        rvFamilyMember.setAdapter(addMemberAdapter);
        addMemberAdapter.setOnItemClickListener((adapter, view, position) -> {
            PromptUserListBean.RowsBean item = addMemberAdapter.getData().get(position);
            if (item != null) {
                addMemberAdapter.setSelected(position, item.getFaceId());
            }
        });

        addMemberDialog.getView().findViewById(R.id.btn_cancel).setOnClickListener(v -> addMemberDialog.dismiss());
        addMemberDialog.getView().findViewById(R.id.btn_close).setOnClickListener(v -> addMemberDialog.dismiss());
        addMemberDialog.getView().findViewById(R.id.btn_confirm).setOnClickListener(v ->
                viewModel.addFamilyMember(addMemberAdapter.getSelectedUsers()));
        if (addMemberDialog.getWindow() != null) {
            addMemberDialog.getWindow().setLayout(964, 670);
            addMemberDialog.getWindow().setBackgroundDrawable(new android.graphics.drawable.ColorDrawable(0));
        }
    }

}